package com.junson.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 代码清单 2-1 EchoServerHandler
 *
 * @author <a href="mailto:norman.maurer@gmail.com">Norman Maurer</a>
 */
//标示一个ChannelHandler可以被多个 Channel 安全地共享
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
	private Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //将消息记录到控制台
        //将接收到的消息写给发送者，而不冲刷出站消息
    	
    	if ("心跳包".equals(msg.toString())) {
    		logger.debug("===>" + msg.toString());
		}else {
			logger.debug("===>" + msg.toString());
			ctx.write(Unpooled.copiedBuffer("收到，谢谢！", CharsetUtil.UTF_8));
	        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
		}
        
    }

//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        //将未决消息冲刷到远程节点，并且关闭该 Channel
//    	ctx.write(Unpooled.copiedBuffer("收到，谢谢！", CharsetUtil.UTF_8));
//        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
//           .addListener(ChannelFutureListener.CLOSE);
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
        Throwable cause) {
        //打印异常栈跟踪
        cause.printStackTrace();
        //关闭该Channel
        ctx.close();
    }
}
